<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Resources;

use App\Services\TreeService;
use Illuminate\Database\Eloquent\Builder;

/**
 * 权限菜单模块资源
 * Class MenuResource
 * @package App\Http\Resources
 */
class MenuResource extends BaseResource
{
    /**
     * @param \Illuminate\Http\Request $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        // 角色模块菜单对应的权限列表
        $role_permission_config = $this->menuPermission()->whereIn('menu_permission.permission_id', function ($query) {
            $query->from('permission')->select('permission.id')
                ->where('parent_id', '!=', 0)
                ->where('public_type', '0');// 通用类型为登录、公共、模块通用不展示
        })->get();

        $role_permission_config = collect($role_permission_config)->map(function ($item) {
            return ['id' => $item->permission_id, 'name' => $item->permission->name, 'parent_id' => $item->permission->parent_id, 'priv' => $item->permission->priv];
        })->toArray();

        // 已分配权限id集
        $permission_ids = [];
        $permission_items = [];
        collect($this->menuPermission)->each(function ($item) use (&$permission_ids, &$permission_items) {
            $permission_ids[] = $item->permission_id;
            if (!empty($item->permission->priv)) {
                $permission_items[] = ['id' => $item->permission_id, 'name' => $item->permission->name, 'priv' => $item->permission->priv];
            }
        });

        // 资源
        return $this->filterFields([
            'id' => $this->id,
            'type' => $this->type,
            'parent_id' => $this->parent_id,
            'name' => $this->name,
            'enname' => $this->enname,
            'description' => $this->description,
            'sort' => $this->sort,
            'route_name' => $this->route_name,
            'route_icon' => $this->route_icon,
            'route_path' => $this->route_path,
            'route_component' => $this->route_component,
            'route_redirect' => $this->route_redirect,
            'route_activeMenu' => $this->route_activeMenu,
            'route_alwaysShow' => $this->route_alwaysShow,
            'route_affix' => $this->route_affix,
            'route_breadcrumb' => $this->route_breadcrumb,
            'route_isTree' => $this->route_isTree,
            'sort' => $this->sort,
            'relation_cate' => $this->relation_cate,
            'status' => $this->status,
            'permission_ids' => $permission_ids,
            'permission_items' => $permission_items,
            'role_permission_config' => $role_permission_config,
            'created_at' => $this->created_at ? $this->created_at->format('Y-m-d H:i:s') : "",
            'updated_at' => $this->updated_at ? $this->updated_at->format('Y-m-d H:i:s') : "",
        ]);
    }
}
